﻿using RssReader.DataModel;
using RssReader.Feeds;
using Windows.ApplicationModel.Search;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using System.Linq;

// The User Control item template is documented at http://go.microsoft.com/fwlink/?LinkId=234236

namespace RssReader
{
    public sealed partial class AddCategoryPopup : UserControl
    {
        readonly Popup _popup;
        private readonly CategoryHelper _categoryHelper = new CategoryHelper();
        private GroupedItemsPage _groupedItemsPage;
        public AddCategoryPopup(Popup popup1, GroupedItemsPage groupedItemsPage)
        {
            _popup = popup1;
            _groupedItemsPage = groupedItemsPage;
            this.InitializeComponent();
        }

        private void Save_new_category_click(object sender, RoutedEventArgs e)
        {
            Save_category_to_collection();
        }

        private async void Save_category_to_collection()
        {
            var categories = await _categoryHelper.Get_all_categories();
            var categoryExists =
                categories.FirstOrDefault(category => category.Name.ToLower() == txtCategoryName.Text.ToLower());

            if (categoryExists == null)
            {
                categories.Insert(0, new Category {Name = txtCategoryName.Text, Url = txtCategoryFeedUrl.Text, Visible = true});
                _categoryHelper.Put_categories(categories);
                _popup.IsOpen = false;

                if (_groupedItemsPage != null)
                {
                    _groupedItemsPage.Get_feed();
                    _groupedItemsPage = null;
                }

            }
        }

        private void Cancel_click(object sender, RoutedEventArgs e)
        {
            _popup.IsOpen = false;
            SearchPane.GetForCurrentView().ShowOnKeyboardInput = true;
        }
    }
}
